package org.mic.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.util.HTTPRequestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by luoxiaofei on 2017/6/9.
 */
@Configuration
@Component
public class ResponseServerFilter extends ZuulFilter {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${zuul.open}")
    private boolean open;

    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        long startTime = (long) ctx.get("startTime");
        long endTime = System.currentTimeMillis();

        logger.info(String.format("request path:%s, ip %s, response run time:%s", request.getServletPath(), HTTPRequestUtils.getInstance().getClientIP(request), (endTime - startTime)));

        return null;
    }

    public boolean shouldFilter() {
        return open;
    }

    public int filterOrder() {
        return 1;
    }

    public String filterType() {
        return "post";
    }
}
